/*

Plugin for streamlining animation callbacks

Example:

$('.wizzbang')
	.slideUp()
	.then()
	.html('')
	.addClass('loading')
	.fadeIn();

// Do ajax stuff here. Also, TODO: ajax support?

$('.wizzbang')
	.fadeOut()
	.then()
	.removeClass('loading')
	.html(ajax_data)
	.slideDown();
	

*/

(function($) {

// placeholder object returned from .then()
var dummy = function($object) {
	this.is_a_dummy = true;
}

$.fn.then = function(fn) {
	// If you supply a function, the function will simply be called with this as the argument.
	// Seems to work, not really tested
	if ( fn ) {
		fn(this);
		return this;
	}

	// If this is our dummy object just return it.
	// This happens when more than one .then is called in a chain.
	if ( this.is_a_dummy ) return this;

	var $this = $(this);

	var d = new dummy();

	// Loop through the jQuery object and make dummy functions for the jQuery methods
	// This could probably be done better -
	// __noSuchMethod__ would be a nice addition when it's supported
	for ( thing in $this ) {
		if ( typeof $this[thing] == 'function' ) {
			d[thing] = (function(name) {
				return function() {
					var args = arguments || [];
					// Make a function to be called in proper qeueud order
					var callback = function(next, hooks) {
						$this[name].apply($this, args);
						next();
					};
					$this.queue(callback);
					return d;
				};
			})(thing)
		}
	}

	return d;
};

})(jQuery);